<?php
class TestQuestions extends CActiveRecord {
	
	public static function model($className = __CLASS__) {
		return parent::model($className);
	}

	public function tableName() {
		return strtolower('PsyTestQuestions');
	}
	
	public function rules() {
		return array(
            array('questionOrder, question', 'required'),
            array('questionOrder', 'numerical')
		);
	}

    public function defaultScope() {
        return array(
            'order' => 'questionOrder ASC'
        );
    }
    public function attributeLabels() {
        return array(
            'question' => '题目',
            'questionOrder' => '题目序号'
        );
    }

    public function relations() {
        return array(
            'answers' => array(self::HAS_MANY, 'TestAnswers', 'questionId',
                'joinType'=> 'LEFT JOIN',
                'order' => 'answerOrder'
            ),
            'topic' => array(self::BELONGS_TO, 'TestTopics', 'topicId',
                'joinType' => 'LEFT JOIN',
            )
        );
    }
    
	public function afterDelete() {
		foreach($this->answers as $answer) {
			$answer->afterDelete();
		}
		TestAnswers::model()->deleteAll('questionId = '.$this->questionId);

        TestTopics::model()->updateByPk($this->topicId, array('questionCount' => self::model()->count('topicId = '.$this->topicId)));
	}

    public function afterSave() {
    	if($this->isNewRecord) {
        	TestTopics::model()->updateByPk($this->topicId, array('questionCount' => self::model()->count('topicId = '.$this->topicId)));
    	}
    }
	
    public function getCurrentQuestion($topic) {
        $state = $topic->getState();
        $criteria = new CDbCriteria;
        if($topic->getTypeCatalog() == 'mark') {
            $ids = array_keys($state);
            $lastId = 0;
            if($ids) {
                $lastId = array_pop($ids);
                $lastQuestion = self::model()->findByPk($lastId);
                $criteria->condition = 'topicId = '.$topic->topicId.' AND questionOrder > '.$lastQuestion->questionOrder;
            } else {
                $criteria->condition = 'topicId = '.$topic->topicId.' AND questionOrder >= 0';
            }
            $criteria->order = 'questionOrder ASC';
        } else if($topic->getTypeCatalog() == 'jumping') {
            $answerId = array_pop($state);
            if($answerId !== null) {
                $linkage = TestAnswerLinkage::model()->findByAttributes(array('answerId' => $answerId, 'linkType' => TestAnswerLinkage::LINKTYPE_QUESTION));
                if($linkage !== null) {
                    $questionId = $linkage->linkToId;
                    $criteria->condition = 'questionId = '.$questionId;
                } else {
                    return null;
                }
            } else {
                $criteria->condition = 'topicId = '.$topic->topicId.' AND questionOrder >= 0';
            }
        }
        return self::model()->with('answers')->find($criteria);
    }
}
